package com.property.demo.controller;

import com.property.demo.dto.ApiResponse;
import com.property.demo.dto.BuildingDTO;
import com.property.demo.model.Building;
import com.property.demo.service.BuildingService;
import com.property.demo.util.SortUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
@RequestMapping("/api/buildings")
public class BuildingController {

    @Autowired
    private BuildingService buildingService;

    @GetMapping
    public ResponseEntity<?> getAllBuildings(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long communityId,
            @RequestParam(required = false) String name,
            @RequestParam(defaultValue = "id,desc") String[] sort) {
        
        try {
            List<Sort.Order> orders = SortUtil.getOrders(sort);
            Pageable pageable = PageRequest.of(page, size, Sort.by(orders));
            
            Page<Building> buildingsPage;
            if (communityId != null || (name != null && !name.isEmpty())) {
                buildingsPage = buildingService.findByFilters(communityId, name, pageable);
            } else {
                buildingsPage = buildingService.findAll(pageable);
            }
            
            List<BuildingDTO> buildingDTOs = buildingsPage.getContent().stream()
                    .map(BuildingDTO::new)
                    .collect(Collectors.toList());
            
            Map<String, Object> response = new HashMap<>();
            response.put("content", buildingDTOs);
            response.put("currentPage", buildingsPage.getNumber());
            response.put("totalItems", buildingsPage.getTotalElements());
            response.put("totalPages", buildingsPage.getTotalPages());
            
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(
                new ApiResponse(false, "获取楼栋列表失败: " + e.getMessage()),
                HttpStatus.INTERNAL_SERVER_ERROR
            );
        }
    }

    @GetMapping("/all")
    public ResponseEntity<List<BuildingDTO>> getAllBuildingsNoPage() {
        List<Building> buildings = buildingService.findAll();
        List<BuildingDTO> buildingDTOs = buildings.stream()
                .map(BuildingDTO::new)
                .collect(Collectors.toList());
        return new ResponseEntity<>(buildingDTOs, HttpStatus.OK);
    }

    @GetMapping("/{id}")
    public ResponseEntity<BuildingDTO> getBuildingById(@PathVariable Long id) {
        Building building = buildingService.findById(id);
        BuildingDTO buildingDTO = new BuildingDTO(building);
        return new ResponseEntity<>(buildingDTO, HttpStatus.OK);
    }

    @PostMapping
    public ResponseEntity<ApiResponse> createBuilding(@RequestBody Building building) {
        Building savedBuilding = buildingService.save(building);
        BuildingDTO buildingDTO = new BuildingDTO(savedBuilding);
        return new ResponseEntity<>(
                new ApiResponse(true, "Building created successfully", buildingDTO),
                HttpStatus.CREATED);
    }

    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse> updateBuilding(
            @PathVariable Long id, @RequestBody Building buildingDetails) {
        Building updatedBuilding = buildingService.update(id, buildingDetails);
        BuildingDTO buildingDTO = new BuildingDTO(updatedBuilding);
        return new ResponseEntity<>(
                new ApiResponse(true, "Building updated successfully", buildingDTO),
                HttpStatus.OK);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse> deleteBuilding(@PathVariable Long id) {
        buildingService.delete(id);
        return new ResponseEntity<>(
                new ApiResponse(true, "Building deleted successfully"),
                HttpStatus.OK);
    }

    @GetMapping("/community/{communityId}")
    public ResponseEntity<List<BuildingDTO>> getBuildingsByCommunityId(@PathVariable Long communityId) {
        List<Building> buildings = buildingService.findByCommunityId(communityId);
        List<BuildingDTO> buildingDTOs = buildings.stream()
                .map(BuildingDTO::new)
                .collect(Collectors.toList());
        return new ResponseEntity<>(buildingDTOs, HttpStatus.OK);
    }

    @GetMapping("/search")
    public ResponseEntity<List<BuildingDTO>> searchBuildings(
            @RequestParam String name, @RequestParam Long communityId) {
        List<Building> buildings = buildingService.findByNameContainingAndCommunityId(name, communityId);
        List<BuildingDTO> buildingDTOs = buildings.stream()
                .map(BuildingDTO::new)
                .collect(Collectors.toList());
        return new ResponseEntity<>(buildingDTOs, HttpStatus.OK);
    }
} 